var format = function (data, fId, fParent) {
    while (_.any(data, function (v) {
        return typeof v.path == 'undefined';
    })) {
        data = _.map(data, function (v) {
            if (!v[fParent]) {
                v.path = '' + v[fId];
                return v;
            }
            var parent = _.find(data, function (v2) {
                return v2[fId] == v[fParent];
            });
            if (!parent) {
                v.path = '' + v[fId];
                return v;
            }
            if (!parent.path) {
                return v;
            }
            v.path = parent.path + '/' + v[fId];
            return v;
        });
    }
    return data;
};

var tree = function (e) {
    e.preventDefault();
    var eData = document.getElementById('data');
    try {
        var data = JSON.parse(eData.value);
    } catch (e) {
        console.log(e);
    }
    var eId = document.getElementById('id');
    var fId = eId.value;
    var eParent = document.getElementById('parent');
    var fParent = eParent.value;
    var eName = document.getElementById('name');
    var fName = eName.value;
    var formated = format(data, fId, fParent);
    var sorted = _.sortBy(formated, 'path');
    var maped = _.map(sorted, function (v) {
        var tab = v.path.split('/').length;
        var tab = _.map(_.range(0, tab), function (t) {
            return '';
        }).join('  ');
        return tab + (typeof v[fName] !== 'undefined' ? v[fName] : JSON.stringify(v));
    });
    document.getElementById('tree').innerHTML = maped.join('\n');
};
